<template>
  <Form
    :schema="schema"
    :model="eventVal"
    @register="formRegister"
    :isCol="false"
    label-width="240px"
  />
</template>

<script>
import { FlowEventList } from '@/flow/config/flowConfig'
import { Set } from '@/flow/api/flowNodeEvent'
import { GetItems } from '@/flow/api/flowInter'
import { useForm } from '@/hooks/web/useForm'
import { Form } from '@/components/Form'
const { formRegister, formMethods } = useForm()
export default {
  components: {
    Form
  },
  props: {
    nodeId: {
      type: String,
      default: null
    },
    flowId: {
      type: String,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    nodeEvent: {
      type: Object,
      default: null
    },
    filterEvent: {
      type: Function,
      default: null
    },
    isLoad: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      schema: [],
      eventVal: {},
      eventList: []
    }
  },
  watch: {
    isLoad: {
      handler(val) {
        if (val) {
          this.initNodeEvent()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.inititems()
  },
  methods: {
    formRegister,
    initScheme() {
      const list = FlowEventList.filter((c) => this.filterEvent(c.value))
      this.schema = list.map((c) => {
        return {
          field: c.value.toString(),
          label: c.text,
          component: 'Select',
          componentProps: {
            disabled: this.readonly,
            clearable: true,
            options: this.eventList.filter((a) => (c.value & a.UseRange) === c.value),
            props: {
              label: 'InterName',
              value: 'Id'
            },
            placeholder: c.text + '审批事件',
            on: {
              change: (val) => {
                this.saveEvent(c, val)
              }
            }
          }
        }
      })
    },
    initNodeEvent() {
      const ev = this.nodeEvent ? Object.assign({}, this.nodeEvent) : {}
      FlowEventList.forEach((c) => {
        const k = c.value.toString()
        if (k in ev == false) {
          ev[k] = null
        }
      })
      this.eventVal = ev
      console.log(ev)

      this.initScheme()
    },
    async saveEvent(item, val) {
      const id = item.value
      await Set({
        FlowId: this.flowId,
        NodeId: this.nodeId,
        EventType: id,
        EventId: val
      })
      this.$emit('update:nodeEvent', this.eventVal)
    },
    async inititems() {
      this.eventList = await GetItems()
    }
  }
}
</script>
